package com.tlgen.orm.utils.orm;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.tlgen.orm.annotation.*;
import com.tlgen.orm.annotation.Collection;
import com.tlgen.orm.model.BaseEntity;
import com.tlgen.orm.param.MiddleParams;
import com.tlgen.orm.param.QueryParams;
import com.tlgen.orm.param.RelationParams;
import com.tlgen.orm.support.QueryOperator;
import com.tlgen.orm.utils.reflect.ReflectionUtils;
import com.tlgen.orm.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.lang.reflect.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

import static com.tlgen.orm.constant.QueryOperatorConstant.ORDER_BY_DESC;
import static com.tlgen.orm.constant.SQLScript.*;
import static com.tlgen.orm.enums.Anno.ASSOCIATION;
import static com.tlgen.orm.enums.Anno.COLLECTION;
import static com.tlgen.orm.utils.reflect.ReflectionUtils.getObjectFieldValues;
import static com.tlgen.orm.utils.StringUtils.uncapUnderline;

/**
 * ORM 注解反射工具类
 */
@Slf4j
public class ORMUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(ORMUtils.class);

    // 主键字段名缓存（类 -> 主键字段名）
    private static final ConcurrentMap<Class<?>, String> PRIMARY_KEY_CACHE = new ConcurrentHashMap<>();

    // 表名缓存（类 -> 表名）
    private static final ConcurrentMap<Class<?>, String> TABLE_NAME_CACHE = new ConcurrentHashMap<>();

    // 高性能优化版本
    private static final ConcurrentMap<Class<?>, String> LOGICAL_FIELD_CACHE = new ConcurrentHashMap<>();
    private static final String OBJECT_SIMPLE_NAME = "Object";

    // 获取主键字段名（带缓存和多级父类查找）
    public static String getPrimaryKey(Class<?> clazz) {
        // 检查缓存
        String cachedKey = PRIMARY_KEY_CACHE.get(clazz);
        if (cachedKey != null) {
            return cachedKey;
        }

        // 递归查找主键字段
        String primaryKey = findPrimaryKeyRecursive(clazz);

        // 缓存结果
        if (primaryKey != null) {
            PRIMARY_KEY_CACHE.put(clazz, primaryKey);
        }

        return primaryKey != null ? primaryKey : "";
    }

    // 获取主键字段名（实例方法）
    public static String getPrimaryKey(Object entity) {
        if (entity == null) {
            return "";
        }
        return getPrimaryKey(entity.getClass());
    }

    // 递归查找主键字段
    private static String findPrimaryKeyRecursive(Class<?> clazz) {
        // 终止条件：到达Object类
        if (clazz == null || clazz == Object.class) {
            return null;
        }

        // 在当前类中查找主键字段
        for (Field field : clazz.getDeclaredFields()) {
            // 检查Id注解
            if (field.isAnnotationPresent(Id.class)) {
                // 检查FieldName注解
                if (field.isAnnotationPresent(FieldName.class)) {
                    return field.getAnnotation(FieldName.class).value();
                }
                // 默认使用字段名转换
                return uncapUnderline(field.getName());
            }
        }

        // 递归查找父类
        return findPrimaryKeyRecursive(clazz.getSuperclass());
    }

    // 获取表名（带缓存）
    public static String getTableName(Class<?> clazz) {
        // 检查缓存
        String cachedName = TABLE_NAME_CACHE.get(clazz);
        if (cachedName != null) {
            return cachedName;
        }

        // 获取表名
        String tableName = resolveTableName(clazz);

        // 缓存结果
        TABLE_NAME_CACHE.put(clazz, tableName);

        return tableName;
    }

    // 解析表名
    private static String resolveTableName(Class<?> clazz) {
        // 检查TableName注解
        if (clazz.isAnnotationPresent(TableName.class)) {
            TableName tableNameAnno = clazz.getAnnotation(TableName.class);
            try {
                // 直接获取value方法的值
                Method valueMethod = TableName.class.getMethod("value");
                return (String) valueMethod.invoke(tableNameAnno);
            } catch (Exception e) {
                // 回退到toString表示
                return tableNameAnno.toString();
            }
        }

        // 默认使用类名转换
        return StringUtils.classNameToTableName(clazz);
    }

    // 获取实体类中一对一模型关联属性字段(优化版)
    public static <T> List<RelationParams> getAssociationFields(Class<T> tClass) {
        List<RelationParams> associationParamsList = new ArrayList<>();

        // 使用流式处理简化代码
        Arrays.stream(tClass.getDeclaredFields())
                .filter(field -> field.isAnnotationPresent(Association.class))
                .forEach(field -> {
                    // 获取注解
                    Association associationAnno = field.getAnnotation(Association.class);

                    // 创建关联参数对象
                    RelationParams params = new RelationParams();
                    params.setColumnName(field.getName());
                    params.setColumnType(field.getType().getName());
                    params.setRelationType(ASSOCIATION.getValue());
                    params.setRelationName(associationAnno.relate());
                    params.setColumnValue("");

                    associationParamsList.add(params);
                });

        return associationParamsList;
    }

    // 获取实体类中模型关联一对多属性字段
    public static <T> List<RelationParams> getCollectionFields(Class<T> tClass) {
        return Arrays.stream(tClass.getDeclaredFields())
                .filter(field -> field.isAnnotationPresent(Collection.class))
                .map(field -> {
                    Collection collectionAnno = field.getAnnotation(Collection.class);

                    RelationParams params = new RelationParams();
                    params.setMasterClass(tClass);
                    params.setColumnName(field.getName());

                    // 关键修复：获取List的泛型类型
                    Type genericType = field.getGenericType();
                    if (genericType instanceof ParameterizedType) {
                        ParameterizedType pt = (ParameterizedType) genericType;
                        Type[] actualTypes = pt.getActualTypeArguments();
                        if (actualTypes.length > 0 && actualTypes[0] instanceof Class) {
                            // 这里获取到真正的泛型类型（如Book.class）
                            Class<?> elementClass = (Class<?>) actualTypes[0];
                            params.setColumnType(elementClass.getName());
                            params.setRelationClass(elementClass);
                        }
                    }

                    // 处理中间表类型
                    Class<?> middleClass = collectionAnno.middle();
                    if (middleClass != null && !middleClass.equals(void.class)) {
                        params.setRelationClass(middleClass);
                        params.setHasMiddleClass(true);
                    }

                    params.setRelationType(COLLECTION.getValue());
                    params.setColumnValue("");

                    return params;
                })
                .collect(Collectors.toList());
    }

    // 根据属性的基本数据类型、包装类型调用其 getter 方法获取值
    public static <T> String getFieldValue(T t, Field field)
            throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        // 属性值
        String value = "";
        // 判断是否有关联模型注解, 如果有就忽略
        Association associationAnno = field.getAnnotation(Association.class);
        Collection collectionAnno = field.getAnnotation(Collection.class);
        if (null == associationAnno && null == collectionAnno) {
            // 如果类型是  String
            if (field.getGenericType().toString().equals(
                    "class java.lang.String")) { // 如果type是类类型，则前面包含"class "，后面跟类名
                // 拿到该属性的 getter 方法
                Method m = (Method) t.getClass().getMethod(
                        "get" + getMethodName(field.getName()));
                String val = (String) m.invoke(t); // 调用 getter 方法获取属性值
                if (null != val) {
                    value = val;
                }
            }

            // 如果类型是 Integer
            if (field.getGenericType().toString().equals(
                    "class java.lang.Integer")) {
                Method m = (Method) t.getClass().getMethod(
                        "get" + getMethodName(field.getName()));
                Integer val = (Integer) m.invoke(t);
                if (val != null) {
                    value = String.valueOf(val);
                }

            }

            // 如果类型是 Double
            if (field.getGenericType().toString().equals(
                    "class java.lang.Double")) {
                Method m = (Method) t.getClass().getMethod(
                        "get" + getMethodName(field.getName()));
                Double val = (Double) m.invoke(t);
                if (val != null) {
                    value = String.valueOf(val);
                }

            }

            // 如果类型是 Boolean 是封装类
            if (field.getGenericType().toString().equals(
                    "class java.lang.Boolean")) {
                Method m = (Method) t.getClass().getMethod(
                        field.getName());
                Boolean val = (Boolean) m.invoke(t);
                if (val != null) {
                    value = String.valueOf(val);
                }

            }

            // 如果类型是  boolean 基本数据类型不一样 这里有点说名如果定义名是 isXXX 的 那就全都是 isXXX 的
            // 反射找不到 getter 的具体名
            if (field.getGenericType().toString().equals("boolean")) {
                Method m = (Method) t.getClass().getMethod(
                        field.getName());
                Boolean val = (Boolean) m.invoke(t);
                if (val != null) {
                    value = String.valueOf(val);
                }

            }
            // 如果类型是 Date
            if (field.getGenericType().toString().equals(
                    "class java.util.Date")) {
                Method m = (Method) t.getClass().getMethod(
                        "get" + getMethodName(field.getName()));
                Date val = (Date) m.invoke(t);
                if (val != null) {
                    value = String.valueOf(val);
                }

            }
            // 如果类型是 Short
            if (field.getGenericType().toString().equals(
                    "class java.lang.Short")) {
                Method m = (Method) t.getClass().getMethod(
                        "get" + getMethodName(field.getName()));
                Short val = (Short) m.invoke(t);
                if (val != null) {
                    value = String.valueOf(val);
                }
            }
        }
        // 返回属性值
        return value;
    }

    // 根据字段名获取字段值(原始对象值)
    public static String getJavaFieldName(Class<?> clazz, String columnName) {

        // 如果没有找到，尝试将下划线转换为驼峰命名
        String camelCaseName = toCamelCase(columnName);
        for (Field field : clazz.getDeclaredFields()) {
            if (field.getName().equals(camelCaseName)) {
                return camelCaseName;
            }
        }

        // 最后尝试在父类中查找
        Class<?> superClass = clazz.getSuperclass();
        while (superClass != null && !superClass.equals(Object.class)) {
            for (Field field : superClass.getDeclaredFields()) {
                if (field.getName().equals(camelCaseName)) {
                    return camelCaseName;
                }
            }
            superClass = superClass.getSuperclass();
        }

        return null;
    }

    // 将下划线命名转换为驼峰命名
    private static String toCamelCase(String columnName) {
        StringBuilder result = new StringBuilder();
        boolean nextUpper = false;

        for (int i = 0; i < columnName.length(); i++) {
            char c = columnName.charAt(i);
            if (c == '_') {
                nextUpper = true;
            } else {
                if (nextUpper) {
                    result.append(Character.toUpperCase(c));
                    nextUpper = false;
                } else {
                    result.append(c);
                }
            }
        }
        return result.toString();
    }

    // 修改 getFieldValue 方法，支持通过数据库列名获取值
    public static Object getFieldValue(Object obj, String fieldOrColumnName) {
        try {
            // 首先尝试直接获取字段
            try {
                return getFieldValueDirect(obj, fieldOrColumnName);
            } catch (NoSuchFieldException e) {
                // 如果失败，尝试将列名转换为字段名
                String javaFieldName = getJavaFieldName(obj.getClass(), fieldOrColumnName);
                if (javaFieldName != null) {
                    return getFieldValueDirect(obj, javaFieldName);
                }
                throw e;
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to get field value for: " + fieldOrColumnName, e);
        }
    }

    // 直接获取字段值的方法
    private static Object getFieldValueDirect(Object obj, String fieldName)
            throws NoSuchFieldException, IllegalAccessException {
        Class<?> clazz = obj.getClass();
        while (clazz != null) {
            try {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                return field.get(obj);
            } catch (NoSuchFieldException e) {
                clazz = clazz.getSuperclass();
            }
        }
        throw new NoSuchFieldException("Field not found: " + fieldName);
    }

    /**
     * 智能ID生成器
     */
    public static <T> void generateEntityId(T entity) {
        try {
            // 1. 获取ID字段
            Field idField = getPrimaryKeyField(entity.getClass());
            if (idField == null) return;

            // 2. 确保ID字段可访问
            idField.setAccessible(true);

            // 3. 检查ID是否为空
            Object currentValue = idField.get(entity);
            if (currentValue != null) {
                // 已有ID值不处理
                return;
            }

            // 4. 根据ID字段类型自动生成合适的ID
            Class<?> idType = idField.getType();

            // 长整型ID（如 Long）
            if (long.class.equals(idType) || Long.class.equals(idType)) {
                idField.set(entity, IdWorker.nextId());
            }
            // 字符串ID（如 String）
            else if (String.class.equals(idType)) {
                idField.set(entity, String.valueOf(IdWorker.nextId()));
            }
            // 有时候继承了 BaseEntity, 但是没有设定主键类型, 那默认就是使用 Long
            else if (Object.class.equals(idType)) {
                idField.set(entity, IdWorker.nextId());
            }
            // 更多类型可根据需要扩展...

        } catch (Exception e) {
            log.error("Failed to generate ID for entity", e);
        }
    }

    /**
     * 递归查找主键字段（包含父类）
     */
    public static Field getPrimaryKeyField(Class<?> clazz) {
        // 检查输入
        if (clazz == null || clazz == Object.class) {
            return null;
        }

        // 1. 查找当前类的@Id注解字段
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(Id.class)) {
                return field;
            }
        }

        // 2. 查找当前类的"id"字段
        try {
            return clazz.getDeclaredField("id");
        } catch (NoSuchFieldException ignored) {
            // 继续尝试
        }

        // 3. 尝试其他常见主键名（当前类）
        for (String name : new String[]{"uuid", "uid", "key", "oid", "pk"}) {
            try {
                return clazz.getDeclaredField(name);
            } catch (NoSuchFieldException ignored) {
            }
        }

        // 4. 递归查找父类（关键改进）
        Class<?> superClass = clazz.getSuperclass();
        if (superClass != null && superClass != Object.class) {
            Field superIdField = getPrimaryKeyField(superClass);
            if (superIdField != null) {
                return superIdField;
            }
        }

        // 5. 尝试接口中的字段（可选）
        for (Class<?> interfaceClass : clazz.getInterfaces()) {
            try {
                // 接口中只支持public字段
                Field idField = interfaceClass.getField("id");
                if (idField != null) {
                    return idField;
                }
            } catch (NoSuchFieldException ignored) {
            }
        }

        return null;
    }

    // 获取属性的 getter 方法名
    public static String getMethodName(String fieldName) {
        byte[] items = fieldName.getBytes();
        items[0] = (byte) ((char) items[0] - 'a' + 'A');
        return new String(items);
    }

    // 获取中间表映射数据
    public static <T> List<MiddleParams> getMiddleMappingParams(Class<T> tClass) {
        List<MiddleParams> middleParamsList = Lists.newArrayList();
        // 获取中间表表名
        TableName tableNameAnnotation = tClass.getAnnotation(TableName.class);
        String tableName = "";
        if (null != tableNameAnnotation) {
            tableName = tableNameAnnotation.name();
        }
        // 获取映射
        Field[] fields = tClass.getDeclaredFields();
        for (Field field : fields) {
            // 获取映射的表名
            MappingClass annotation = field.getAnnotation(MappingClass.class);
            if (null != annotation) {
                // 中间表映射数据
                MiddleParams middleParams = new MiddleParams();
                // 设置中间表类型
//                middleParams.setMasterClass(tClass);
                // 设置中间表名称
                middleParams.setTableName(tableName);
                middleParams.setMappingClass(annotation.value());
                // 根据映射类型获取数据库表
                String mappingTableName = getTableName(annotation.value());
                middleParams.setMappingTableName(mappingTableName);
                // 获取映射的属性字段名
                FieldName fieldNameAnnotation = field.getAnnotation(FieldName.class);
                if (null != fieldNameAnnotation) {
                    middleParams.setMappingColumn(fieldNameAnnotation.value());
                } else {
                    middleParams.setMappingColumn(field.getName());
                }
                // 保存中间表映射数据
                middleParamsList.add(middleParams);
            }
        }
        return middleParamsList;
    }


    // 获取逻辑删除属性
    public static <T> String getLogicalDeleteField(Class<T> tClass) {
        // 优先尝试缓存
        return LOGICAL_FIELD_CACHE.computeIfAbsent(tClass, cls -> {
            // 深度优先搜索继承链
            String fieldName = searchInheritanceChain(cls);
            return fieldName != null ? uncapUnderline(fieldName) : DEL_FLAG;
        });
    }

    private static String searchInheritanceChain(Class<?> cls) {
        // 当前类搜索
        String fieldName = findLogicalFieldInClass(cls);
        if (fieldName != null) return fieldName;

        // 递归搜索继承链
        Class<?> superClass = cls.getSuperclass();
        while (superClass != null && !OBJECT_SIMPLE_NAME.equals(superClass.getSimpleName())) {
            fieldName = findLogicalFieldInClass(superClass);
            if (fieldName != null) return fieldName;
            superClass = superClass.getSuperclass();
        }
        return null;
    }

    private static String findLogicalFieldInClass(Class<?> cls) {
        // 先尝试所有字段（避免创建Field对象）
        for (java.lang.reflect.Field field : cls.getDeclaredFields()) {
            if (isLogicalField(field)) {
                return field.getName();
            }
        }
        return null;
    }

    // 高效检查逻辑字段（减少反射调用）
    private static boolean isLogicalField(java.lang.reflect.Field field) {
        // 快速排除：检查是否可能是逻辑字段
        if (!field.getName().toLowerCase().contains("del")) return false;

        // 正式检查注解
        return Arrays.stream(field.getDeclaredAnnotations())
                .anyMatch(anno -> AsLogicalField.class.equals(anno.annotationType()));
    }

    public static <T> QueryOperator<T> getQueryOperator(Object object) {
        QueryOperator<T> queryOperator = new QueryOperator<>();
        Map<String, Object> map = getObjectFieldValues(object);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (Objects.nonNull(entry.getValue())) {
                queryOperator.eq(entry.getKey(), entry.getValue());
            }
        }
        return queryOperator;
    }

    //--- save 辅助方法 ---//
    public static List<Field> getAllFields(Class<?> clazz) {
        List<Field> fields = new ArrayList<>();
        while (clazz != null && !clazz.equals(Object.class)) {
            Collections.addAll(fields, clazz.getDeclaredFields());
            clazz = clazz.getSuperclass();
        }
        // 过滤掉不需要处理的字段
        return fields.stream()
                .filter(field -> !shouldSkipField(field)) // 应用过滤条件
                .collect(Collectors.toList());
    }

    /**
     * 判断字段是否需要跳过（根据注解）
     */
    private static boolean shouldSkipField(Field field) {
        // 1. 过滤 @AsNotField 注解的字段
        if (field.isAnnotationPresent(AsNotField.class)) {
            return true;
        }

        // 3. 过滤静态字段
        if (Modifier.isStatic(field.getModifiers())) {
            return true;
        }

        // 4. 忽略特殊字段
        if ("serialVersionUID".equals(field.getName())) return true;
        // 4. 可以根据需要添加更多过滤条件
        // 例如：过滤特定名称的字段

        return false;
    }

    // 获取查询参数列表, 过滤掉不作为数据库映射的字段
    public static <T> List<QueryParams> getQueryParamsList(QueryOperator<T> queryOperator, Class<?> tClass) {
        // 获取实体类的所有字段名（下划线格式）
        Set<String> validFields = getAllFields(tClass).stream()
                .map(field -> uncapUnderline(field.getName()))
                .collect(Collectors.toSet());

        // 过滤出有效的查询参数
        return queryOperator.getParamsList().stream()
                .filter(param -> validFields.contains(param.getColumn()))
                .collect(Collectors.toList());
    }

    public static boolean shouldGenerateId(Object o, String primaryKey) {
        return ReflectionUtils.getFieldValue(o, primaryKey) == null;
    }

    // 解析实体类ID的实际类型(考虑泛型参数)
    public static Class<?> resolveActualIdType(Object entity) {
        // 1. 获取实体的实际运行时类
        Class<?> clazz = entity.getClass();

        // 2. 遍历所有超类查找泛型信息
        while (clazz != null) {
            // 3. 检查是否为泛型基类
            Type genericSuperclass = clazz.getGenericSuperclass();
            if (genericSuperclass instanceof ParameterizedType) {
                ParameterizedType paramType = (ParameterizedType) genericSuperclass;

                // 4. 提取泛型参数的实际类型
                if (paramType.getRawType().getTypeName().equals(BaseEntity.class.getName())) {

                    Type[] typeArgs = paramType.getActualTypeArguments();
                    if (typeArgs.length > 0 && typeArgs[0] instanceof Class) {
                        return (Class<?>) typeArgs[0];
                    }
                }
            }
            clazz = clazz.getSuperclass(); // 继续向上查找
        }

        // 5. 尝试通过反射获取ID字段的实际类型
        try {
            String primaryKeyFieldName = getPrimaryKey(entity);
            Field idField = entity.getClass().getDeclaredField(primaryKeyFieldName);
            return idField.getType();
        } catch (Exception e) {
            // 6. 默认返回String类型
            return String.class;
        }
    }

    public static Object generateIdByType(Class<?> idType) {
        long nextId = IdWorker.nextId(); // 所有分支共享同一个ID值，避免多次调用产生不同ID

        if (idType == String.class) {
            return String.valueOf(nextId); // 直接转为字符串
        } else if (idType == Long.class || idType == long.class) {
            return nextId;
        } else if (idType == Integer.class || idType == int.class) {
            // 安全处理大数值
            if (nextId > Integer.MAX_VALUE) {
                LOGGER.warn("Generated ID {} exceeds Integer.MAX_VALUE, using truncated value", nextId);
                return (int) (nextId % Integer.MAX_VALUE);
            }
            return (int) nextId; // 直接强转比字符串转换高效
        } else if (idType == BigDecimal.class) {
            return BigDecimal.valueOf(nextId).setScale(0, RoundingMode.UNNECESSARY); // 确保整数精度
        } else {
            return handleCustomIdType(idType, nextId); // 处理自定义类型
        }
    }

    // 处理自定义ID类型生成
    private static Object handleCustomIdType(Class<?> idType, long nextId) {
        // 尝试使用带Long参数的构造方法
        for (Constructor<?> constructor : idType.getConstructors()) {
            if (constructor.getParameterCount() == 1 &&
                    constructor.getParameterTypes()[0] == Long.class) {
                try {
                    return constructor.newInstance(nextId);
                } catch (Exception e) {
                    LOGGER.error("Failed to construct {} with Long: {}", idType.getName(), e.getMessage());
                }
            }
        }

        // 尝试无参构造
        try {
            Object idObj = idType.getDeclaredConstructor().newInstance();
            if (idObj instanceof Serializable) {
                try {
                    Method setMethod = idType.getMethod("setId", Long.class);
                    setMethod.invoke(idObj, nextId);
                    return idObj;
                } catch (Exception e) {
                    LOGGER.debug("No setId(Long) method in {}", idType.getName());
                }
            }
            return idObj;
        } catch (Exception e) {
            LOGGER.error("Failed to create custom ID object: {}", e.getMessage());
            return String.valueOf(nextId); // 最终回退为字符串
        }
    }

    public static Object getProcessedFieldValue(Object o, Field field, String primaryKey, Object nextId) {
        String fieldName = field.getName();
        Object value = ReflectionUtils.getFieldValue(o, fieldName);

        // 1. 处理主键
        if (fieldName.equals(primaryKey) && value == null && nextId != null) {
            value = nextId;
            ReflectionUtils.setFieldValue(o, fieldName, nextId);
        }

        // 2. 处理逻辑删除字段
        if (field.isAnnotationPresent(AsLogicalField.class)) {
            return 0;
        }

        // 3. 处理特殊字段
        return processSpecialFields(o, field, value);
    }

    public static Object processSpecialFields(Object o, Field field, Object value) {
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        // 如果字段值类型与字段声明类型不匹配，进行智能转换
        if (value != null && !field.getType().isInstance(value)) {
            return convertValueToType(value, field.getType());
        }

        // 创建时间自动填充
        if ("createTime".equals(fieldName) && value == null) {
            return handleTimeAutoFill(o, field);
        }

        // 日期类型格式化
        if (isTemporalType(fieldType)) {
            return formatTemporalValue(value);
        }

        return value;
    }

    public static Object handleTimeAutoFill(Object o, Field field) {
        Object timeValue = null;

        if (field.getType().equals(Date.class)) {
            timeValue = new Date();
        } else if (field.getType().equals(LocalDateTime.class)) {
            timeValue = LocalDateTime.now();
        } else if (field.getType().equals(LocalDate.class)) {
            timeValue = LocalDate.now();
        }

        ReflectionUtils.setFieldValue(o, field.getName(), timeValue);
        return timeValue;
    }

    public static boolean isTemporalType(Class<?> type) {
        return TemporalAccessor.class.isAssignableFrom(type) || Date.class.isAssignableFrom(type);
    }

    public static Object formatTemporalValue(Object value) {
        if (value == null) return null;

        if (value instanceof Date) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format((Date) value);
        } else if (value instanceof LocalDateTime) {
            return ((LocalDateTime) value).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } else if (value instanceof LocalDate) {
            return ((LocalDate) value).format(DateTimeFormatter.ISO_LOCAL_DATE);
        }

        return value;
    }

    public static String formatValues(List<Object> values) {
        return values.stream()
                .map(v -> {
                    if (v == null) return "null";

                    // 日期类型已格式化，直接处理
                    if (v instanceof String && isDateLikeString((String) v)) {
                        return "'" + ((String) v).replace("'", "''") + "'";
                    }

                    // 原始类型直接使用
                    if (v instanceof Number || v instanceof Boolean) {
                        return v.toString();
                    }

                    // 其他类型安全转义
                    return "'" + v.toString().replace("'", "''") + "'";
                })
                .collect(Collectors.joining(", "));
    }

    public static boolean isDateLikeString(String value) {
        // 简化验证逻辑，实际应使用正则表达式
        return value.length() >= 10 && value.charAt(4) == '-' && value.charAt(7) == '-';
    }

    public static String buildInsertSQL(Class<?> clazz, List<String> columns, String valuesPart) {
        return INSERT_PREFIX + getTableName(clazz) +
                SEPARATOR_OPEN + String.join(SEPARATOR_COMMA, columns) + SEPARATOR_CLOSE +
                INSERT_VALUES +
                SEPARATOR_OPEN + valuesPart + SEPARATOR_CLOSE;
    }

    public static <T> String buildBatchInsertSQL(T o) {
        Class<?> aClass = o.getClass();
        // 递归收集所有层级的字段
        List<Field> allFields = getAllFields(aClass);
        // 收集属性名
        List<String> columns = new ArrayList<>();
        // 收集属性对应的值
        List<Object> values = new ArrayList<>();
        for (Field field : allFields) {
            String fieldName = field.getName();
            Object fieldValue = ReflectionUtils.getFieldValue(o, field.getName());
            values.add(fieldValue);
            columns.add(uncapUnderline(fieldName));
        }
        // 处理值
        StringBuffer stringBuffer = new StringBuffer();
        values.forEach(x -> {
            if (null != x) {
                stringBuffer.append(SEPARATOR_SINGLE_QUOTA.concat(String.valueOf(x)).concat("', "));
            } else {
                stringBuffer.append(x).append(", ");
            }
        });
        String bufferString = stringBuffer.toString();
        if (!bufferString.isEmpty()) {
            bufferString = bufferString.substring(0, stringBuffer.length() - 2);
        }
        // 组装 SQL
        return INSERT_PREFIX
                .concat(getTableName(aClass))
                .concat(SEPARATOR_OPEN)
                .concat(String.join(SEPARATOR_COMMA, columns))
                .concat(SEPARATOR_CLOSE)
                .concat(INSERT_VALUES)
                .concat(SEPARATOR_OPEN)
                .concat(bufferString)
                .concat(SEPARATOR_CLOSE);
    }

    // 值类型转换工具方法
    public static Object convertValueToType(Object value, Class<?> targetType) {
        if (value == null) return null;

        if (targetType == String.class) {
            return String.valueOf(value);
        } else if (targetType == Long.class || targetType == long.class) {
            return toLong(value);
        } else if (targetType == Integer.class || targetType == int.class) {
            return toInt(value);
        } else if (targetType == BigDecimal.class) {
            return toBigDecimal(value);
        } else {
            // 其他复杂类型需要开发者自行处理
            throw new IllegalArgumentException("无法将类型 " + value.getClass() +
                    " 转换为 " + targetType +
                    "。需要自定义类型转换器");
        }
    }

    // 类型转换辅助方法
    public static Long toLong(Object value) {
        if (value instanceof Number) {
            return ((Number) value).longValue();
        } else if (value instanceof String) {
            return Long.parseLong((String) value);
        }
        throw new ClassCastException("无法转换为Long类型: " + value);
    }

    public static Integer toInt(Object value) {
        if (value instanceof Number) {
            return ((Number) value).intValue();
        } else if (value instanceof String) {
            return Integer.parseInt((String) value);
        }
        throw new ClassCastException("无法转换为Integer类型: " + value);
    }

    public static BigDecimal toBigDecimal(Object value) {
        if (value instanceof Number) {
            return new BigDecimal(value.toString());
        } else if (value instanceof String) {
            return new BigDecimal((String) value);
        }
        throw new ClassCastException("无法转换为BigDecimal类型: " + value);
    }

    // ======== 游标分页工具方法 =========

    public static String addCursorCondition(String sql, String cursorField, Long cursorValue, boolean orderByDesc) {
        if (cursorValue == null) {
            // 没有游标值时，只需确保排序方向
            return ensureOrderBy(sql, cursorField, orderByDesc);
        }

        // 构建条件部分（不包含排序）
        String condition = orderByDesc
                ? cursorField + " < " + cursorValue
                : cursorField + " > " + cursorValue;

        // 智能添加条件（WHERE 或 AND）
        String whereClause = sql.contains("WHERE") ? " AND " : " WHERE ";
        String conditionalSql = sql + whereClause + condition;

        // 确保有正确的排序子句
        return ensureOrderBy(conditionalSql, cursorField, orderByDesc);
    }

    /**
     * 确保SQL有正确的排序子句
     */
    private static String ensureOrderBy(String sql, String cursorField, boolean orderByDesc) {
        if (sql.contains("ORDER BY")) {
            return sql;
        }

        String orderDirection = orderByDesc ? "DESC" : "ASC";
        return sql + " ORDER BY " + cursorField + " " + orderDirection;
    }

    public static String addLimitClause(String sql, int pageSize) {
        return sql + SEPARATOR_LIMIT + pageSize;
    }

    public static <T> boolean isDescOrder(QueryOperator<T> queryOperator, Class<T> tClass) {
        return ORMUtils.getQueryParamsList(queryOperator, tClass).stream()
                .anyMatch(param -> Objects.equals(ORDER_BY_DESC, param.getColumn()) &&
                        Objects.equals("true", String.valueOf(param.getValue())));
    }

    public static Long parseCursorValue(String cursor) {
        if (StrUtil.isBlank(cursor)) return null;
        try {
            return Long.parseLong(cursor);
        } catch (Exception e) {
            log.error("Invalid cursor: " + cursor, e);
            return null;
        }
    }

    // 获取关联表的外键字段名（基于relate值）
    public static String getForeignKeyField(Class<?> relationClass, String relateField) {
        // 1. 尝试直接使用relateField作为字段名
        try {
            Field field = relationClass.getDeclaredField(relateField);
            return getColumnName(field);
        } catch (NoSuchFieldException e) {
            // 继续尝试其他方法
        }

        // 2. 尝试查找匹配的字段（忽略大小写）
        for (Field field : relationClass.getDeclaredFields()) {
            if (field.getName().equalsIgnoreCase(relateField)) {
                return getColumnName(field);
            }
        }

        // 3. 尝试查找Long类型的字段（常见的外键类型）
        for (Field field : relationClass.getDeclaredFields()) {
            if (field.getType().equals(Long.class) || field.getType().equals(long.class)) {
                return getColumnName(field);
            }
        }

        return null;
    }

    // 获取字段对应的数据库列名
    public static String getColumnName(Class<?> clazz, String fieldName) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            return getColumnName(field);
        } catch (NoSuchFieldException e) {
            return camelToUnderline(fieldName);
        }
    }

    // 获取字段对应的数据库列名
    private static String getColumnName(Field field) {
        if (field.isAnnotationPresent(FieldName.class)) {
            return field.getAnnotation(FieldName.class).value();
        }
        return camelToUnderline(field.getName());
    }

    // 驼峰转下划线
    private static String camelToUnderline(String camel) {
        if (camel == null || camel.isEmpty()) {
            return camel;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < camel.length(); i++) {
            char c = camel.charAt(i);
            if (Character.isUpperCase(c)) {
                if (i > 0) {
                    sb.append('_');
                }
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    private static final Map<Class<?>, List<Field>> DELETE_FIELDS_CACHE = new ConcurrentHashMap<>();

    public static List<Field> getDeleteFields(Class<?> clazz) {
        return DELETE_FIELDS_CACHE.computeIfAbsent(clazz, k -> {
            List<Field> fields = new ArrayList<>();
            Class<?> current = clazz;
            while (current != Object.class) {
                for (Field field : current.getDeclaredFields()) {
                    if (field.isAnnotationPresent(AsMiddleDeleteField.class)) {
                        field.setAccessible(true);
                        fields.add(field);
                    }
                }
                current = current.getSuperclass();
            }
            return Collections.unmodifiableList(fields);
        });
    }

}
